#!/usr/bin/env bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
source $DIR/../../lib/shell/common.sh
source $DIR/../../lib/shell/env.sh

function start_irqbalance(){
    systemctl start irqbalance
    if [ $? != 0 ];then
        echo "failed to start irqbalance"
        return 1
    fi
    systemctl status irqbalance > /dev/null
    if [ $? != 0 ];then
        echo "failed to start irqbalance"
        return 1
    fi
    return 0
}

function stop_irqbalance(){
    systemctl stop irqbalance
    if [ $? != 0 ];then
        echo "failed to stop irqbalance"
        return 1
    fi
    systemctl status irqbalance > /dev/null
    if [ $? != 3 ];then
        echo "failed to stop irqbalance"
        return 1
    fi
    return 0
}

function client_run() {
    echo "start client connect"
    client_cmd="iperf3 -t $IPERF3_RUNTIME -i $IPERF3_INTERVAL -P $IPERF3_PROCESS_NUM -f g -c $lts_ip"
    run_cmd "$client_cmd" &
}

function server_kill() {
    server_down="kill -9 \`pidof iperf3\` &>/dev/null"
    $ESSH $lts_ip $server_down || return 1
    return 0
}

function server_run() {
    echo "start server listen"
    server_kill
    server_cmd="iperf3 -sD"
    $ESSH $lts_ip $server_cmd &
    if [ $? -eq 0 ]; then
        echo "server listen success"
        sleep 3
        return 0
    else
        echo "server listen failed"
        return 1
    fi
}

function irqbalance_test(){

    IPERF3_LOG=irqbalance_test_log.iperf3

    origin="stopped"
    systemctl status irqbalance > /dev/null
    if [ $? != 3 ]; then
        stop_irqbalance || return 1
        origin="started"
    fi

    [ -z "$LTS_IPADDRESS" ] && { echo "Error: LTS IP are required, but none are given";exit 1; }
    lts_ip=$(echo $LTS_IPADDRESS | awk '{print $1}')

    server_run
    [ $? -ne 0 ] && return 1

    if ps -ef|grep iperf3|grep -w $IPERF3_PORT >/dev/null 2>&1;then
        kill -9 `ps -ef|grep iperf3|grep -w $IPERF3_PORT|awk '{print $2}'`
    fi

    client_run 
    sleep 5

    start_irqbalance || return 1

    wait
    server_kill || return 1

    if [ "$origin" == "stopped" ]; then
        stop_irqbalance || return 1
    fi

    if test -f "$IPERF3_LOG"; then
        rm -rf $IPERF3_LOG
    fi

    return 0
}

# # # # # # # # main # # # # # # # #
print_test_info "Network"
bash ../../../utils/sshconf.sh setup
trap "bash ../../../utils/sshconf.sh restore" EXIT
stress_network_env 1 $RUNTIME
irqbalance_test && test_pass || test_fail